﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using Microsoft.SharePoint.Client;
using System.Collections.ObjectModel;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Automation;
using System.Windows.Controls.Primitives;
using System.Collections.Generic;

namespace UI{
	public partial class MainPage : UserControl{
		
		ClientContext context;
        List floorPlansList,listOfPrinters;
        ListItemCollection allCampus,allPrinters;
        GroupCollection allGroups;
        Group printerAdminsGroup;
        UserCollection printerAdmins;
        User currentUser;
        Popup printerPopup,addPrinterPopup;
        Ellipse draggingCirc, placedCirc;
        int timerKey,closeKey;
        string[] fluff;
        bool isAllowed,enabled,poppedUp;
        public MainPage(){
			InitializeComponent();
            isAllowed = enabled = poppedUp = false;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
		}

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            draggingCirc = makeCircle();
            BitmapImage bmimg = new BitmapImage();
            bmimg.UriSource = new Uri("homePage.png", UriKind.Relative);
            bg.Source = bmimg;
            context = ClientContext.Current;

            Guid listGuid = new Guid("C4BAA325-B3E6-4A48-BF04-B43B68DB0C64");//list of the campuses and their buildings - changed
            floorPlansList = context.Web.Lists.GetById(listGuid);
            context.Load(floorPlansList);
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"<View><Query></Query><RowLimit>10000</RowLimit></View>";
            allCampus = floorPlansList.GetItems(camlQuery);
            context.Load(allCampus);
            currentUser = context.Web.CurrentUser;
            context.Load(currentUser);
            allGroups = context.Site.RootWeb.SiteGroups;
            context.Load(allGroups);
            printerAdminsGroup = allGroups.GetById(684);
            context.Load(printerAdminsGroup);
            printerAdmins = printerAdminsGroup.Users;
            context.Load(printerAdmins);
            context.ExecuteQueryAsync(success, null);
        }
		private void success(Object sender, ClientRequestSucceededEventArgs args){
			Dispatcher.BeginInvoke(whatever);
		}
		private void whatever(){
            TreeDataSource d = new TreeDataSource(allCampus);
            Tree.ItemsSource = d;
            foreach (User u in printerAdmins)
            {
                if (u.LoginName.Equals(currentUser.LoginName))
                {
                    isAllowed = true;
                    break;
                }
            }
            if (isAllowed)
            {
                options.Visibility = System.Windows.Visibility.Visible;
            }
        }
		private void TreeViewItem_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            TextBlock item = (TextBlock)sender;
            
            createMap(item.Tag.ToString());

		}
		public void createMap(string img){
			BitmapImage bmimg = new BitmapImage();
            bmimg.UriSource = new Uri(context.Url.ToString()+@"/Campus pictures/" + img + ".png");
            
			bg.Source = bmimg;
            content.Children.Clear();
            string b = img.Substring(0, img.IndexOf(" Floor"));
            string f = img.Substring(img.IndexOf("Floor") + 6, 1);
            fluff = new string[1] {b};
            Guid PrinterGuid = new Guid("258B877C-A031-4B3C-BF01-F6CA9A9FD0DD");//list of the printers - changed
            listOfPrinters = context.Web.Lists.GetById(PrinterGuid);
            context.Load(listOfPrinters);
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"<View><Query><Where><And><Eq><FieldRef Name='building'/><Value Type='Text'>" + b + @"</Value></Eq><Eq><FieldRef Name='floor'/><Value Type='Text'>" + f + @"</Value></Eq></And></Where></Query><RowLimit>1000</RowLimit></View>";
            allPrinters = listOfPrinters.GetItems(camlQuery);
            context.Load(allPrinters);
            context.ExecuteQueryAsync(OnRequestSucceeded,null);

		}
        private void OnRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
        {
            Dispatcher.BeginInvoke(populatePrinters);
        }
        public void populatePrinters(){
            
            foreach (ListItem item in allPrinters)
            {
                string[] data = new string[2] { item["Script_x0020_URL"].ToString(), item["Title"].ToString() };
                Ellipse r = makeCircle();
                r.Visibility = System.Windows.Visibility.Visible;
                r.MouseEnter += new MouseEventHandler(r_MouseEnter);
                r.MouseLeave += new MouseEventHandler(r_MouseLeave);
                r.Tag = data;
                content.Children.Add(r);
                setCoord(r,new Point(Double.Parse(item["x"].ToString()),Double.Parse(item["y"].ToString())));
            }
        }

        void r_MouseLeave(object sender, MouseEventArgs e)
        {
            bool t = UIHelper.ClearTimeout(timerKey);
            
        }
        private void r_MouseEnter(object sender,System.Windows.Input.MouseEventArgs e)
        {
            timerKey = UIHelper.SetTimeout(400, () => installPopup(sender, e));
        }
        private void installPopup(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (!poppedUp)
            {
                printerPopup = new System.Windows.Controls.Primitives.Popup();
                content.Children.Add(printerPopup);
                ChildWindow1 pop = new ChildWindow1(sender, isAllowed);
                pop.Background = new SolidColorBrush(Color.FromArgb(255, 239, 241, 243));
                printerPopup.Child = pop;
                setCoord(printerPopup, new Point(e.GetPosition(content).X, e.GetPosition(content).Y - pop.DesiredSize.Height));
                printerPopup.IsOpen = true;
                pop.MouseLeave += new MouseEventHandler(popcont_MouseLeave);
                pop.MouseEnter += new MouseEventHandler(pop_MouseEnter);
                poppedUp = true;
                closeKey = UIHelper.SetTimeout(1000, () => closeInstall());
            }
        }

        void pop_MouseEnter(object sender, MouseEventArgs e)
        {
            bool t = UIHelper.ClearTimeout(closeKey);
        }
        
        void popcont_MouseLeave(object sender, MouseEventArgs e)
        {
            closeKey = UIHelper.SetTimeout(500, () => closeInstall());
        }
        private void closeInstall()
        {
            printerPopup.IsOpen = false;
            poppedUp = false;
            side.Children.Remove(printerPopup);
        }
        private void setCoord(System.Windows.UIElement o, Point p)
        {
            Canvas.SetLeft(o, p.X);
            Canvas.SetTop(o, p.Y);
        }
        private void setCoord(System.Windows.UIElement o, Point p, int offsetX, int offsetY)
        {
            setCoord(o, new Point(p.X - offsetX, p.Y - offsetY));
        }

        private void options_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            enabled = true;
            options.Background = new SolidColorBrush(Color.FromArgb(255, 59, 89, 152));
            options.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 59, 89, 152));
        }

        private void content_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (isAllowed && enabled)
            {
                content.Children.Add(draggingCirc);
                //content.Cursor = Cursors.None;
                draggingCirc.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void adding_MouseMove(object sender, MouseEventArgs e)
        {
            if (isAllowed && enabled)
            {
                //content.Cursor = Cursors.None;
                Canvas.SetLeft(draggingCirc, e.GetPosition(LayoutRoot).X - 249);
                Canvas.SetTop(draggingCirc, e.GetPosition(LayoutRoot).Y - 40);
            }
        }
        
        private Ellipse makeCircle()
        {
            Ellipse ellipse = new Ellipse();
            ellipse.Visibility = System.Windows.Visibility.Collapsed;
            ellipse.Height = ellipse.Width = 12;
            ellipse.Fill = new SolidColorBrush(Color.FromArgb(255, 56, 148, 255));
            return ellipse;
        }
        private void adding_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isAllowed && enabled)
            {
                Point pt = e.GetPosition(null);

                    draggingCirc.Visibility = Visibility.Collapsed;
                    placedCirc = makeCircle();
                    content.Children.Remove(draggingCirc);
                    content.Children.Add(placedCirc);
                    setCoord(placedCirc, pt, 249, 40);
                    AddPrinter ap = new AddPrinter(fluff,pt);
                    ap.cancleButton.Click += new RoutedEventHandler(cancleButton_Click);
                    ap.saveButton.Click += new RoutedEventHandler(saveButton_Click);
                    addPrinterPopup = new System.Windows.Controls.Primitives.Popup();
                    content.Children.Add(addPrinterPopup);
                    addPrinterPopup.Child = ap;
                    setCoord(addPrinterPopup, pt, 249, 40);
                    addPrinterPopup.IsOpen = true;
                    enabled = false;
                    placedCirc.Visibility = System.Windows.Visibility.Visible;
                
            }
        }

        void saveButton_Click(object sender, RoutedEventArgs e)
        {
            AddPrinter ap = addPrinterPopup.Child as AddPrinter;
            string[] data = ap.datareturn();
            placedCirc.Tag = data;
            placedCirc.MouseEnter += new MouseEventHandler(r_MouseEnter);
            content.Children.Remove(addPrinterPopup);
        }

        void cancleButton_Click(object sender, RoutedEventArgs e)
        {
            content.Children.Remove(placedCirc);
            content.Children.Remove(addPrinterPopup);
        }

        private void options_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            options.Background = new SolidColorBrush(Color.FromArgb(255, 56, 148, 255));
            options.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 56, 148, 255));
        }

        private void options_MouseEnter(object sender, MouseEventArgs e)
        {
            options.Background = new SolidColorBrush(Color.FromArgb(255, 56, 148, 255));
            options.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 56, 148, 255));
        }

        private void options_MouseLeave(object sender, MouseEventArgs e)
        {
            options.Background = new SolidColorBrush(Color.FromArgb(255, 59, 89, 152));
            options.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 59, 89, 152));
        }
    }
    public static class UIHelper
    {
        private static Dictionary<int, DispatcherTimerContainingAction> m_Timers;

        // static constructor 
        static UIHelper()
        {
            m_Timers = new Dictionary<int, DispatcherTimerContainingAction>();
        }

        public static int SetTimeout(int milliseconds, Action func)
        {
            int timerKey = new Random().Next(0, 1000000);
            var timer = new DispatcherTimerContainingAction
            {
                Interval = new TimeSpan(0, 0, 0, 0, milliseconds),
                Action = func,
            };

            m_Timers.Add(timer.GetHashCode(), timer);
            timer.Tick += _onTimeout;
            timer.Start();
            return timer.GetHashCode();
        }

        public static bool ClearTimeout(int TimerHashCode)
        {
            bool retVal = false;
            try
            {
                DispatcherTimerContainingAction timer = m_Timers[TimerHashCode];
                timer.Stop();
                timer.Action = null;
                timer.Tick -= _onTimeout;
                if (m_Timers.Remove(TimerHashCode))
                {
                    retVal = true;
                }
                timer = null;
            }
            catch (KeyNotFoundException)
            {
            }
            return retVal;
        }

        private static void _onTimeout(object sender, EventArgs arg)
        {
            var t = sender as DispatcherTimerContainingAction;
            try
            {
                m_Timers.Remove(t.GetHashCode());
            }
            catch (ArgumentNullException)
            {
            }
            t.Stop();
            t.Action();
            t.Tick -= _onTimeout;
        }
    }

    public class DispatcherTimerContainingAction : System.Windows.Threading.DispatcherTimer
    {
        public Action Action { get; set; }
    }
}